package com.zzptc.fragmenttest1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zzptc.fragmenttest1.Bean.User;

import org.litepal.LitePal;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private Button registerbtn,loginbtn;
    private TextView usnedit,psdedit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setListener();
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usnedit.getText().toString().trim();
                String psd=psdedit.getText().toString().trim();
                User user=confirmUser(usn,psd);
                if (user==null){
                    showToast("账号密码错误");
                }else {
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                }
            }
        });
        registerbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usnedit.getText().toString().trim();
                String pwd=psdedit.getText().toString().trim();
               User user=new User(0,usn,pwd);
               if (user.save()){
                   showToast("注册成功");
               }else {
                   showToast("该用户已经存在，请重新登录");
               }
            }
        });
    }
    private void showToast(String str){
        Toast.makeText(LoginActivity.this,str, Toast.LENGTH_SHORT).show();
    }
    private User confirmUser(String usn,String psd){
        List<User>userList= LitePal.findAll(User.class);
        for (User u:userList){
            if (usn.equals(u.getName())&&psd.equals(u.getPassword())){
                return u;
            }
        }
        return null;
    }

    private void initView() {
        registerbtn=findViewById(R.id.btn_sw_reg);
        loginbtn=findViewById(R.id.btn_sw_login);
        usnedit=findViewById(R.id.et_sw_name);
        psdedit=findViewById(R.id.et_sw_pwd);
    }
}
